package toubiao.utils.filter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import utils.UtilCollection;
import utils.UtilJackson;


    /**
    * @ClassName: OrderHqlFactory
    * @Description: 根据json 返回 Hql 语句中的 排序语句
    * Json格式：[
    * 			{"className":"project","classField":"seq","orderType":"asc"},
    * 			"className":"project","classField":"name","orderType":"desc"}
    * 		  ];
    * 
    * Hql："	project.seq asc	, project.name desc "
    * 
    * 注意 其中	project 和 name 可根据Convert对象 转换成其他 字符串
    * @author 宁少林
    * @date 2016年11月4日
    *
    */
public class OrderHqlFactory {
	
	static public List<OrderCondition> json2OrderConditionList(String json){
		if(json==null || json.trim().equals("")){
			json="[]";
		}
		
		List<OrderCondition> orderConditionList=new ArrayList<>();
		try {
			orderConditionList = UtilJackson.me().json2List(json, OrderCondition.class);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return orderConditionList;
	}
	
	public static String buildOrderHqlByList(List<OrderCondition> orderConditionList,Map<String, WebClass> webClassMap){
		String orderHql=" order by ";
		if(UtilCollection.isNullOrEmpty(orderConditionList)){
			return orderHql;
		}
		for(OrderCondition orderCondition:orderConditionList){
			String orderPart=buildOrderHql(orderCondition,webClassMap);
			if(orderHql.equals(" order by ")){
				orderHql=orderHql+orderPart;
			}else{
				orderHql=orderHql+" , "+orderPart;
			}
		}
		return orderHql;
	}
	
	
	    /**
	    * @Title: buildOrderHql
	    * @Description: 生成Order 元素,如 project.investAmout asc，如在webClassMap 有对应的model 类名和域名的话，进行转换
	    * @param @param orderCondition
	    * @param @param webClassMap
	    * @param @return    
	    * @return String    
	    * @throws
	    */
	public static String buildOrderHql(OrderCondition orderCondition,Map<String, WebClass> webClassMap){
		String orderPart="";
		String webClassName=orderCondition.getClassName();
		String fildName=orderCondition.getClassField();
		String orderType=orderCondition.getOrderType();
		WebClass webClass=webClassMap.get(webClassMap);
		String defaultOrderHql=webClassName+"."+fildName+" "+orderType;
		if(webClass==null){
			return defaultOrderHql;
		}
		WebClassField field=webClass.getFieldMap().get(fildName);
		if(field==null){
			return defaultOrderHql;
		}
		
		String modelClassName=field.getModelClassName();
		String modelFieldName=field.getModelFieldName();
		String converOrderHql=modelClassName+"."+modelFieldName+" "+orderType;
		
		return converOrderHql;
	}
	
}
